package pers.agony.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import pers.agony.pojo.Permission;
import pers.agony.pojo.Role;
import pers.agony.service.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author : Agony
 * @date : Created in 6:15 下午 2021/11/5
 * @Description:
 * @Modified By:
 * @version: : 1.0
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查询用户信息
        pers.agony.pojo.User logUser = userService.findUserByUsername(username);
        //查询到数据，返回User，查询不到信息，返回null
        if(logUser == null){
            return null;
        }
        //构建用户权限集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        //授予角色
        Set<Role> roles = logUser.getRoles();
        if(!CollectionUtils.isEmpty(roles)){
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                //授予权限
                Set<Permission> permissions = role.getPermissions();
                if(!CollectionUtils.isEmpty(permissions)){
                    for (Permission permission : permissions) {
                        authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //User(String, String, Collection<? extends GrantedAuthority>)
        //认证：通过用户名查询用户信息，查到了以后比较前端密码和数据可密码，通过则认证成功
        //授权：authorities集合，给集合添加元素（权限｜角色名称）绑定到user对象
        // string role
//        authorities.add(new SimpleGrantedAuthority("BBB"));
//        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        //密码是明文，就要加{noop}，框架会把前端和数据库密码进行校验
        //UserDetail下的user作用：校验密码，校验权限，存入session
        return new User(username,logUser.getPassword(),authorities);
    }
}
